import { IInputDevice } from '../../interface/IInputDevice';

type ConditionFn = () => boolean;
type ActionFn = () => void;

interface CommandBinding {
    condition: ConditionFn;
    action: ActionFn;
}

export class InputCommand {
    private commands: Map<string, CommandBinding[]> = new Map<
        string,
        CommandBinding[]
    >();

    constructor() {}

    onTrigger(
        handleEvent: string,
        condition: ConditionFn,
        action: ActionFn,
    ) {
        if (!this.commands.has(handleEvent)) {
            this.commands.set(handleEvent, []);
        }
        this.commands.get(handleEvent)!.push({ condition, action });
    }

    offTrigger(name: string) {
        this.commands.delete(name);
    }

    private invokeCommand() {
        for (let key of this.commands.keys()) {
            const commands = this.commands.get(key);
            if (!commands) continue;
            //
            for (let i = 0; i < commands.length; i++) {
                const condition = commands[i].condition;
                const action = commands[i].action;

                if (condition()) {
                    action();
                }
            }
        }
    }

    executeCommand() {
        this.invokeCommand();
    }
}
